const WebSocket = require('ws')

// 创建WebSocket服务器（端口8080）
const wss = new WebSocket.Server({ port: 8080 })

const active24h = [
  {
    name: '有功功率',
    data: [
      ['15:35:19', '33.3'],
      ['15:35:20', '33.3'],
      ['15:35:21', '33.3'],
      ['15:35:24', '33.3'],
      ['15:35:27', '33.3'],
      ['15:35:28', '33.3'],
      ['15:35:29', '33.3'],
      ['15:35:33', '33.3'],
      ['15:35:49', '33.3'],
      ['15:35:53', '33.3'],
      ['15:36:18', '34.02'],
      ['15:36:19', '34.02'],
      ['15:36:28', '34.02'],
      ['15:36:29', '34.02'],
      ['15:36:30', '34.02'],
      ['15:36:32', '34.02'],
      ['15:36:33', '34.02'],
      ['15:36:40', '33.77'],
      ['15:36:42', '33.77'],
      ['15:36:43', '33.77'],
      ['15:36:54', '33.22'],
      ['15:36:56', '33.48'],
      ['15:36:58', '33.48'],
      ['15:37:03', '33.48'],
      ['15:37:05', '33.48'],
      ['15:37:07', '33.72'],
      ['15:37:09', '33.72'],
      ['15:37:10', '33.72'],
      ['15:37:11', '33.72'],
      ['15:37:14', '33.72']
    ]
  }
]
const active30s = []
const reactive24h = []
const reactive30s = []

function generateData() {
  const currentTime = new Date().toTimeString().split(' ')[0] // 获取当前时间（HH:MM:SS）
  const initialValue = (Math.random() * 100).toFixed(2) // 生成一个随机初始值

  // 初始化数据到当前时刻
  active24h[0].data.push([currentTime, initialValue])
  console.log(`初始化数据: ${currentTime}, ${initialValue}`)

  setInterval(() => {
    const currentTime = new Date().toTimeString().split(' ')[0] // 获取当前时间（HH:MM:SS）
    const randomValue = (Math.random() * 100).toFixed(2) // 生成一个随机值（保留两位小数）

    const newDataPoint = [currentTime, randomValue] // 创建新的数据点
    active24h[0].data.push(newDataPoint) // 将新数据点添加到 active24h 数组中

    console.log(newDataPoint) // 输出生成的数据
  }, 1000) // 每秒生成一次数据
}

// 调用函数以开始生成数据
// generateData()

wss.on('connection', (ws) => {
  console.log(' 新的客户端连接')

  // 接收消息
  // ws.on('message',  (message) => {
  //   // console.log(` 收到消息: ${message}`);
  //   // 广播消息给所有客户端
  //   // wss.clients.forEach((client)  => {
  //   //   if (client.readyState  === WebSocket.OPEN) {
  //   //   }
  //   // });
  //   ws.send(JSON.stringify({reactive24h}));
  // });

  // 连接关闭
  ws.on('close', () => {
    console.log(' 客户端断开连接')
  })

  // 主动发送欢迎消息
  ws.send(
    JSON.stringify({
      active24h,
      active30s,
      reactive24h,
      reactive30s
    })
  )

  setInterval(() => {
    const currentTime = new Date().toTimeString().split(' ')[0] // 获取当前时间（HH:MM:SS）
    const initialValue = (Math.random() * 100).toFixed(2) // 生成一个随机初始值

    // 初始化数据到当前时刻
    active24h[0].data.push([currentTime, initialValue])

    ws.send(
      JSON.stringify({
        active24h,
        active30s,
        reactive24h,
        reactive30s
      })
    )
  }, 1000);
})

console.log('WebSocket 服务器已启动，监听 ws://localhost:8080')
